

import cv2
import numpy as np
if __name__=='__main__':
    image=cv2.imread("C:\\Users\\20436\Desktop\huofu.jpg")
    #灰度化
    image_gray=cv2.cvtColor(
        image,
        cv2.COLOR_BGR2GRAY
    )

    #Canny算法
    image_canny=cv2.Canny(
        image_gray,
        10,
        90
    )

    #霍夫变换
    #创建一张黑图
    black=np.zeros(image.shape,dtype=np.uint8)
    #霍夫直线变换
    lines=cv2.HoughLines(
        image_canny,#边缘检测图像
        0.8,#ρ的密度
        np.pi/180,#θ的密度
        90 #投票器累加阈值
    )

    #在黑图上画线
    #降维
    for lin in lines:
        rho,theta=lin[0]#ρ和θ
        #sinθ和cosθ
        sin_theta=np.sin(theta)
        cos_theta=np.cos(theta)
        #垂足坐标
        x0=cos_theta*rho
        y0=sin_theta*rho
        #一个点画不出来加个偏移量找图像外的两个点
        pianyi=1000
        x1=int(x0+pianyi*(-sin_theta))
        y1=int(y0+pianyi*cos_theta)
        x2=int(x0-pianyi*(-sin_theta))
        y2=int(y0-pianyi*cos_theta)
        #画线
        cv2.line(
            black,
            (x1,y1),
            (x2,y2),
            (255,255,0),
            1,
            cv2.LINE_AA

        )

    black1 = np.zeros(image.shape, dtype=np.uint8)
    #统计概率霍夫直线变换
    lines1=cv2.HoughLinesP(
        image_canny,
        0.8,
        np.pi/180,
        90,
        minLineLength=50,# 最短直线长度
        maxLineGap=10# 线距
    )
    for lin1 in lines1:
        x1,y1,x2,y2=lin1[0]#ρ和θ
        #画线
        cv2.line(
            black1,
            (x1,y1),
            (x2,y2),
            (255,255,0),
            1,
            cv2.LINE_AA
        )

    #霍夫圆变换
    #霍夫梯度法
    circles=cv2.HoughCircles(
        image_canny,
        cv2.HOUGH_GRADIENT,
        1,
        0.12,
        param2=15
    )
    print(len(circles))
    for circle in circles:
        x,y,r=circle[0]
        cv2.circle(
            black1,
            (int(x),int(y)),
            int(r),
            (255,255,0),
            2,
            cv2.LINE_AA

        )

    cv2.imshow('image',image_canny)
    cv2.imshow('black1', black1)
    cv2.waitKey(0)








